package com.l.controller.app;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.l.entity.Recharge;
import com.l.pay.app.PayCommonUtil;
import com.l.pay.app.XMLUtil4jdom;
import com.l.service.RechargeService;

/**
 * w微信支付回调
 * 
 * @author 
 * @version 1.0
 */
@Controller
@SuppressWarnings("all")
public class ReceiveWxPayController {
	@Autowired
	RechargeService rechargeService;

	@RequestMapping("/receivewxpay")
	public String receiveWxPay(HttpServletRequest request) throws Exception {
		BufferedReader reader = null;

        reader = request.getReader();
        String line = "";
        String xmlString = null;
        String resXml = "";
        StringBuffer inputString = new StringBuffer();

        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        xmlString = inputString.toString();
        request.getReader().close();
        Map<String, String> map = new HashMap<String, String>();
        map = XMLUtil4jdom.doXMLParse(xmlString);
        String result_code = map.get("result_code");
        String out_trade_no = map.get("out_trade_no");
        String return_code = map.get("return_code");
        if (checkSign(xmlString)) {
        	if ("SUCCESS".equals(result_code)) {
        		// 查询订单信息
				Recharge aliwxpay=rechargeService.query(out_trade_no);
				if (aliwxpay.getStatus()==0) {
					//修改订单状态
					rechargeService.upStatus(out_trade_no);
				}
    		}
        }
        return "redirect:/select";

	}

	private boolean checkSign(String xmlString) {
        Map<String, String> map = null;
        try {
            map = XMLUtil4jdom.doXMLParse(xmlString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String signFromAPIResponse = map.get("sign").toString();
        if (signFromAPIResponse == "" || signFromAPIResponse == null) {
            return false;
        }
        //清掉返回数据对象里面的Sign数据（不能把这个数据也加进去进行签名），然后用签名算法进行签名
        map.put("sign", "");
        //将API返回的数据根据用签名算法进行计算新的签名，用来跟API返回的签名进行比较
        String signForAPIResponse = getSign(map);
        if (!signForAPIResponse.equals(signFromAPIResponse)) {
            //签名验不过，表示这个API返回的数据有可能已经被篡改了
            return false;
        }
        return true;
    }

    public String getSign(Map<String, String> map) {
        SortedMap<Object, Object> signParams = new TreeMap<Object, Object>();
        for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
            signParams.put(stringStringEntry.getKey(), stringStringEntry.getValue());
        }
        signParams.remove("sign");
        String sign = PayCommonUtil.createSign("UTF-8", signParams);
        return sign;
    }

}
